package com.kongyz.demo.threadtest;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * CountDownLatch是一个同步工具类，它允许一个或多个线程一直等待，直到其他线程的操作执行完后再执行。
 *
 * @author kongyz
 */
public class CountDownLatchExample {
    /**
     * 设定请求的数量
     */
    private static final int THREAD_COUNT = 550;
    private static final int CORE_POOL_SIZE = 300;
    private static final int MAX_POOL_SIZE = 300;
    private static final int QUEUE_CAPACITY = 100;
    private static final Long KEEP_ALIVE_TIME = 0L;


    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TimeUnit.MINUTES,
                new LinkedBlockingQueue<>(),
                new ThreadPoolExecutor.CallerRunsPolicy());
        final CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT);
        for (int i = 0; i < THREAD_COUNT; i++) {
            final int threadNum = i;
            threadPool.execute(() -> {
                try {
                    System.out.println("执行子线程：" + threadNum);
                    test(threadNum);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //表示一个请求已经被完成
                    countDownLatch.countDown();
                }
            });
        }
        System.out.println("主线程准备等待！");
        countDownLatch.await();
        threadPool.shutdown();
        System.out.println("完成");

    }

    private static void test(int threadNum) throws InterruptedException {
        //模拟请求耗时操作
        Thread.sleep(1000);
        System.out.println("当前线程数 threadNum:" + threadNum);
        Thread.sleep(1000);
    }

}
